<template>
	<view class="app u-wrap">
		<view class="u-search-box">
			<view class="u-search-inner">
				<u-search v-model="queryForm1.formData.name" placeholder='请输入搜索的内容' :show-action="false" @search="search"> </u-search>
			</view>
		</view>
		<view class="u-menu-wrap">
			<!-- 一级分类 -->
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop1">
				<view
					v-for="(item,index) in data.category" :key="index"
					class="u-tab-item" :class="[category_id1 === item._id ? 'u-tab-item-active' : '']"
					:data-current="index"
					@tap.stop="changeCategory1(item,index)"
				>
					<view class="u-line-1">
						<view class="category-1">{{item.name}}</view>
						<view class="category-2" v-if="category_id1 === item._id">{{subcategoryItemCom.name}}</view>
					</view>
				</view>
			</scroll-view>
			<!-- 二级分类 -->
			<view v-if="showSubcategory && subcategoryCom && subcategoryCom.length>0">
				<view class="subcategory-mask" @click="showSubcategory=false"></view>
				<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view subcategory" :scroll-top="scrollTop2">
					<view
						v-for="(item,index) in subcategoryCom" :key="index"
						class="u-tab-item" :class="[category_id2 === item._id ? 'u-tab-item-active' : '']"
						:data-current="index"
						@tap.stop="changeCategory2(item,index)"
					>
						<text class="u-line-1">{{item.name}}</text>
					</view>
				</scroll-view>
			</view>

			<block v-for="(item,index) in data.goods" :key="index">
				<scroll-view scroll-y class="right-box" v-if="categoryIdsCom === index" @scrolltolower="nextGoodsList(index)">
					<view class="page-view">
						<view class="class-item">
							<view class="item-container">
								<view class="thumb-box" v-for="(goods, goodsIndex) in goodsListCom" :key="goodsIndex" @click="itemClick(goods)">
									<image :src="goods.goods_thumb" mode="aspectFill" />
									<view class="item-info">
										<view class="name u-line-2"> {{ goods.name }} </view>
										<view class="goods-desc"> {{ goods.goods_desc || "" }} </view>
										<!-- <view class="num">
											<view class="num-left">销量：{{ parseInt(goods.initial_sell_count + goods.real_sell_count) }} </view>
											<view class="num-right">库存：{{ stockFn(goods) }}</view>
										</view> -->
										<view class="price">
											<view class="price-left">{{ priceFn(goods) }}</view>
											<view class="price-right" @click.stop="skuShow(goods)">
												<u-icon type="circle" size="50" name="vk-mall-icon-gouwuche"></u-icon>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</block>
		</view>

		<!-- sku选择器组件 -->
		<vk-mall-goods-sku-popup v-model="skuPopup.show" :goods-info="skuPopup.goods" :mode="skuPopup.mode"/>
		<!-- 全局公共浮球导航模块 -->
		<vk-data-float-ball :scroll-top="scrollTop"></vk-data-float-ball>
		<vk-data-loading v-model="loading" delayTime="0"></vk-data-loading>

	</view>
</template>

<script>
	var vk = uni.vk;			// vk依赖
	export default {
		data() {
			return {
				data:{
					category: [], // 用于储存分类数据
					goods:{
						"":{},
						"a":{}
					}, // 用于储存各分类下的商品数据
				},
				// 列表查询请求数据
				queryForm1: {
					// 分页数据
					pagination: {
						pageIndex: 1, //当前页码
						pageSize: 20, //每页显示数量
					},
					// 表单数据源
					formData: {
						category_ids:"", // 商品分类
						name:"", // 商品名称
						keywords:"", // 商品关键字
					},
					// 查询匹配规则
					columns: [
						{ key: "category_ids", mode: "in" },
						{ key: "name", mode: "%%" },
						{ key: "keywords", mode: "%%" }
					],
					// 排序规则
					sortRule: [
						{ name:"sort", type:"asc" }, // desc降序 asc升序
					]
				},
				skuPopup:{
					show:false,
					goods:{},
					mode:2
				},
				loading:false,
				menuHeight: 0, // 左边菜单的高度
				menuItemHeight: 0, // 左边菜单item的高度
				scrollTop: 0, // 页面滚动条位置
				scrollTop1: 0, // 一级分类的当前滚动条位置
				scrollTop2: 0, // 二级分类的当前滚动条位置
				category_id1:"", // 一级分类
				category_id2:"", // 二级分类
				showSubcategory: false,
			}
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			vk = uni.vk;
			this.options = options;
			this.init(options);
		},
		// 监听 - 页面【首次渲染完成时】执行。注意如果渲染速度快，会在页面进入动画完成前触发
		onReady(){},
		// 监听 - 页面每次【显示时】执行(如：前进和返回) (页面每次出现在屏幕上都触发，包括从下级页面点返回露出当前页面)
		onShow() {},
		// 监听 - 页面每次【隐藏时】执行(如：返回)
		onHide() {},
		// 监听 - 点击右上角转发时 https://uniapp.dcloud.io/api/plugins/share.html#onshareappmessage
		onShareAppMessage(options) {
			return vk.myfn.onShareAppMessage({
				options
			});
		},
		methods: {
			// 页面数据初始化函数
			init(options){
				this.getCategoryIndexShow();
				this.getGoodsList();
			},
			// 获取分类列表 + 第一个分类的商品列表
			getCategoryIndexShow(){
				let that = this;
				return vk.callFunction({
					url: 'client/pub.getCategoryIndexShow',
					loading:true,
					data:{
						goodsPageSize: that.queryForm1.pagination.pageSize,
					},
					success: (data) => {
						data.category.unshift({_id:"",name:"全部"});
						that.data.category = data.category;
						that.autoShowSubcategory();
					}
				});
			},
			// 获取商品列表
			getGoodsList(obj={}){
				let that = this;
				let {
					pageIndex = 1
				} = obj;
				return vk.callFunction({
					url: 'client/pub.getGoodsList',
					loading:true,
					data:{
						...that.queryForm1,
						pagination: {
							pageIndex: pageIndex, //当前页码
							pageSize: that.queryForm1.pagination.pageSize, //每页显示数量
						},
					},
					success: (data) => {
						let category_ids = that.categoryIdsCom;
						if (pageIndex === 1) {
							// 第一页
							that.$set(that.data.goods,category_ids,data);
						} else {
							// 下一页
							let item = that.data.goods[category_ids];
							if (data.rows.length == 0) {
								// 无数据时
								item.hasMore = false;
								item.pagination.pageIndex --;
 							} else {
								item.rows = vk.pubfn.arr_concat(item.rows, data.rows, "_id");
							}
						}
					}
				});
			},
			// 加载下一页商品
			nextGoodsList(category_ids){
				let that = this;
				let item = that.data.goods[category_ids];
				//if (typeof item.hasMore === "boolean" && item.hasMore === false) return;
				if (!item.pagination || !item.pagination.pageIndex) item.pagination.pageIndex = 1;
				item.pagination.pageIndex ++;
				that.getGoodsList({
					pageIndex: item.pagination.pageIndex
				});
			},
			// 切换一级分类
			async changeCategory1(item, index) {
				let that = this;
				if(item._id === that.category_id1){
					if (that.showSubcategory) {
						that.showSubcategory = false;
					} else {
						that.autoShowSubcategory();
					}
					return ;
				}
				that.category_id1 = item._id;
				that.category_id2 = "";
				that.queryForm1.formData.category_ids = item._id;
				// 如果为0，意味着尚未初始化
				if(that.menuHeight == 0 || that.menuItemHeight == 0) {
					await that.getElRect('menu-scroll-view', 'menuHeight');
					await that.getElRect('u-tab-item', 'menuItemHeight');
				}
				// 如果该分类下还未加载过商品，则执行获取该分类下的商品
				let goodsItem = that.data.goods[item._id] || {};
				if (vk.pubfn.isNull(goodsItem.rows)) {
					that.getGoodsList();
				}
				that.autoShowSubcategory();
			},
			// 切换二级分类
			changeCategory2(item, index) {
				let that = this;
				if(item._id === that.category_id2) return ;
				that.category_id2 = item._id;
				that.queryForm1.formData.category_ids = item._id;
				// 如果该分类下还未加载过商品，则执行获取该分类下的商品
				let goodsItem = that.data.goods[item._id] || {};
				if (vk.pubfn.isNull(goodsItem.rows)) {
					that.getGoodsList();
				}
				setTimeout(() => {
					that.showSubcategory = false;
				}, 100);
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				let that = this;
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(that);
					query.select('.' + elClass).fields({size: true},res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if(!res) {
							setTimeout(() => {
								that.getElRect(elClass);
							}, 10);
							return ;
						}
						that[dataVal] = res.height;
					}).exec();
				})
			},
			// 商品搜索
			search(value){
				let that = this;
				that.queryForm1.formData.category_ids = "";
				that.category_id1 = "";
				that.category_id2 = "";
				that.getGoodsList();
			},
			// 点击商品
			itemClick(goods){
				vk.myfn.goods.pageToDetail(goods);
			},
			// 显示sku弹窗
			skuShow(item){
				let that = this;
				that.skuPopup.show = true;
				that.skuPopup.goods = item;
			},
			// 价格计算显示
			priceFn(goods){
				let that = this;
				let str = "";
				if (goods.sku_list && goods.sku_list.length > 0) {
					let min = Number.MAX_VALUE;
					let max = 0;
					goods.sku_list.map((item, index) => {
						if (item.price < min) {
							min = item.price;
						}
						if (item.price > max) {
							max = item.price;
						}
					});
					if (min === max) {
						str = `¥${vk.pubfn.priceFilter(min)}`
					} else {
						str = `¥${vk.pubfn.priceFilter(min)} - ${vk.pubfn.priceFilter(max)}`;
					}
				}
				return str;
			},
			// 自动显示二级分类
			autoShowSubcategory(){
				let { vk,subcategoryCom } = this;
				this.showSubcategory = vk.pubfn.isNotNull(subcategoryCom) ? true : false;
			},
			// 根据分类id获取是否有子分类
			getSubcategory(category_id1){
				let { vk } = this;
				if (!category_id1) return [];
				let list = this.data.category;
				let item = vk.pubfn.getListItem(list, "_id", category_id1);
				return item && item.children ? item.children : [];
			}
		},
		computed: {
			// 当前子分类数据
			subcategoryCom(){
				let { category_id1 } = this;
				return this.getSubcategory(category_id1);
			},
			// 当前子分类列表中点击了哪个子分类
			subcategoryItemCom(){
				let { category_id2, subcategoryCom } = this;
				return vk.pubfn.getListItem(subcategoryCom, "_id", category_id2) || {};
			},
			// 商品列表数据
			goodsListCom(){
				let goods = this.data.goods;
				let category_ids = this.categoryIdsCom;
				let item = goods[category_ids] || {};
				return item.rows || [];
			},
			categoryIdsCom(){
				return this.queryForm1.formData.category_ids || "全部";
			}
		}
	}
</script>

<style lang="scss" scoped>
	.menu-scroll-view{
		background-color: var(--bgcolor);
	}
	.u-wrap {
		height: calc(100vh - var(--window-bottom) - var(--window-top));
		display: flex;
		flex-direction: column;
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: #f2f2f2;
		border-radius: 100rpx;
		padding: 0rpx 16rpx;
		width: 100%;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 200rpx;
		height: 100%;
	}

	.u-tab-item {
		height: 110rpx;
		background: var(--bgcolor);
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 26rpx;
		color: #444;
		font-weight: 400;
		line-height: 1;
		.category-1{
			text-align: center;
		}
		.category-2{
			text-align: center;font-size: 24rpx;color: #5c5c5c;margin-top: 6rpx;
		}
	}

	.u-tab-item-active {
		position: relative;
		color: #000;
		font-size: 30rpx;
		font-weight: 600;
		background: #fff;
	}

	.u-tab-item-active::before {
		content: "";
		position: absolute;
		border-left: 4px solid var(--main);
		height: 32rpx;
		left: 0;
		top: 39rpx;
	}

	.u-tab-view {
		height: 100%;
	}

	.right-box {
		flex: 1;
		background-color: #ffffff;
	}

	.page-view {
		padding: 0rpx;
	}

	.class-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.item-container {
		display: flex;
		flex-wrap: wrap;
	}

	.thumb-box {
		width: 100%;
		display: flex;
		margin-bottom: 40rpx;

		image{
			width: 180rpx;
			height: 180rpx;
		}
	}

	.item-info {
		flex: 1;
		margin-left: 10rpx;
		font-weight: normal;
		font-size: 24rpx;
		color: $u-main-color;
		.name{
			height: 80rpx;
			font-size: 28rpx;
		}
		.goods-desc{
			margin-top: 16rpx;
			font-size: 24rpx;
			color: #9a9a9a;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 1;
			overflow: hidden;
		}
		.num{
			margin-top: 16rpx;
			color: #9a9a9a;
			display: flex;
			.num-left{
				flex: 1;
			}
			.num-right{
				flex: 1;
				text-align: right;
			}
		}
		.price{
			display: flex;
			margin-top: 16rpx;
			font-size: 26rpx;
			color: var(--main);
			font-weight: bold;
			.price-left{
				flex: 1;
			}
			.price-right{
				position: relative;
				top:-8rpx
			}
		}
	}

	.subcategory{
		position: fixed;
		left:200rpx;
		z-index: 2;
		background-color: #ffffff;
		border-right:2rpx solid #e6e6e6;
		.u-tab-item {
			background: #ffffff;
		}
	}
	.subcategory-mask{
		position: fixed;
		left:200rpx;
		width: 100vw;
		height: 100vh;
		z-index: 1;
		background-color: transparent;
	}

</style>
